package org.example.object.notify;

import java.util.Random;

public class Producer {
    private final Object lock;
    //缓冲区
    private Object[] buffer;
    private Integer value;

    public Producer(Object lock, Object[] buffer) {
        this.lock = lock;
        this.buffer=buffer;
        value= 1;
    }

    public void produce() {
        //获取锁
        synchronized (lock) {
            //如果缓冲区已满
            while (null!= buffer[0] ) {
                try {
                    //等待
                    lock.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }

            try {
                Thread.sleep(new Random().nextInt(1000));
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //生产
            System.out.println("生产者生产数据：" + value);
            buffer[0] = value++;
            //唤醒所有等待的线程
            lock.notifyAll();
        }
    }
}
